import React, { useState, useEffect } from 'react'
import ReactDOM from 'react-dom/client'
import { RouterProvider } from 'react-router-dom'
import { initializeRouter, routerOld } from '../config/routes'
import { message } from 'antd'
import Loading from './components/loading'
import { storage } from '@/utils/Storage'
import { storeGlobalUser } from '@/store/globalUser'
import { observer } from 'mobx-react'
import { toJS } from 'mobx'
const Main: React.FC = observer(() => {
  const [router, setRouter] = useState<any>(null) // 用来存储初始化后的路由
  const token = storage.get('TOKEN')

  //   临时轮询的方案，后期将关闭
  useEffect(() => {
    if (storeGlobalUser.token) {
      const setupRouter = async () => {
        const initializedRouter = await initializeRouter()
        window.routers = initializedRouter
        const showMsg = storage.get('SHOWMSG')
        setRouter(initializedRouter)
        console.log(window.location.pathname, 'location')
        if (window.location.pathname !== '/login') {
          showMsg !== '1' && message.success('您的当前权限更新完毕')
          storage.set('SHOWMSG', '1')
        }
      }
      setupRouter()
      const intervalId = setInterval(() => {
        setupRouter()
      }, 300000)
      return () => clearInterval(intervalId)
    }
  }, [storeGlobalUser.token])
  //   备用：无需轮询时的逻辑
  //   useEffect(() => {
  //     // 调用异步的 initializeRouter
  //     if(token){
  //       const setupRouter = async () => {
  //         const initializedRouter = await initializeRouter()
  //         // console.log(initializedRouter)
  //         window.routers = initializedRouter
  //         setRouter(initializedRouter)
  //       }
  //       setupRouter()
  //     }
  //   }, [token])

  if (!router) {
    // 路由未加载时显示 Loading
    return <RouterProvider router={routerOld} fallbackElement={<Loading />} />
  }
  return <RouterProvider router={router} fallbackElement={<Loading />} />
})

// 挂载到 DOM 节点
ReactDOM.createRoot(document.getElementById('root') as HTMLElement).render(
  <React.StrictMode>
    <Main />
  </React.StrictMode>
)
